﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace AugustSql
{
    public enum FirstOrLast
    {
        First,
        Last,
    }

    public enum SqlInformationAction
    {
        Add,
        Remove,
        Change
    }

    //public class Constant
    //{
    //    public static string Key = "Id";
    //}

    public class SqlInformationBase : INotifyPropertyChanged
    {
        public static object lock_sql_base = new object();
        public string[] Key;
        public object[] KeyValue;
        public string[] Element;
        public object[] ElementValue;
        public string PrimaryKey;
        public object PrimaryKeyValue;
        public ISqlCollectionBase ParentSqlInformationCollection;
        private SqlInformationBase beforesetsqlinformation = null;
        public event PropertyChangedEventHandler PropertyChanged;

        public SqlInformationBase()
        {


        }
        public void SetBeforeSqlInformation(SqlInformationBase sqlInformationBase)
        {
            beforesetsqlinformation = sqlInformationBase;
        }

        public SqlInformationBase GetBeforeSqlInformation()
        {
            return beforesetsqlinformation;
        }

        public void EditShowDialog(string head = "")
        {
            //PropertyInforItemUserControl.EditShowDialog(this, head);
            this.FindAllPropertyChanged(out var names, out var vals);
            if (names.Count > 0)
            {
                if (MessageBox.Show($"有{names.Count}处变更，是否应用？", "询问", System.Windows.MessageBoxButton.YesNo) == System.Windows.MessageBoxResult.Yes)
                {
                    this.SetSqlInformation();
                    MessageBox.Show("已应用变更！", "", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    MessageBox.Show("未应用变更！", "", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        public void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            PropertyChanged?.Invoke(sender, e);
        }

        public static void InitMySqlInstatnce(object instanceobj)
        {
            var props = instanceobj.GetType().GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            InquirePage MainPage = null;
            foreach (var item in props)
            {
                if (item.GetValue(instanceobj) is null)
                {
                    if (item.PropertyType.IsGenericType && item.PropertyType.ToString().Contains("SqlInformationCollection"))
                    {
                        var p = item.PropertyType.GenericTypeArguments;
                        if (p.Length == 1)
                        {
                            if (p[0].BaseType == typeof(SqlInformationBase))
                            {
                                item.SetValue(instanceobj, typeof(SqlInformationBase).GetMethod("Register", new Type[] { typeof(string), typeof(string), typeof(string), typeof(string), typeof(int) })
                                    .MakeGenericMethod(p[0]).Invoke(null, new object[] { "database", "127.0.0.1", "root", "123456", 3306 }));
                                if (item != null)
                                {
                                    var collection = item.GetValue(instanceobj);
                                    var ocm = collection.GetType().GetProperty("ObserveCollectionManage").GetValue(collection);
                                    if (ocm is ObserveCollectionManage manager && instanceobj is Window window)
                                    {
                                        manager.Window = window;
                                        manager.MaxCount = 300;
                                    }
                                }
                                //自动添加数据源
                                if (InquirePage.NewSql is null)
                                {
                                    var collection = item.GetValue(instanceobj);
                                    var sql = collection.GetType().GetField("newSQL");
                                    InquirePage.NewSql = sql.GetValue(collection);
                                }
                            }
                        }
                    }
                }
                if (item.GetValue(instanceobj) is InquirePage page && MainPage is null)
                {
                    if (page.InquireTableTexts is null || page.InquireTableTexts.Count() == 0 || page.InquireTableNames is null || page.InquireTableNames.Count() == 0)
                    {
                        MainPage = page;
                    }
                }
            }
            if (MainPage != null)
            {
                MainPage.InquireTableNames = SqlInstance.InquirePageNameDic.Keys.ToArray();
                MainPage.InquireTableTexts = SqlInstance.InquirePageNameDic.Values.ToArray();
            }
        }


        public SqlInformationBase Copy()
        {
            SqlInformationBase cell = Activator.CreateInstance(GetType()) as SqlInformationBase;
            foreach (PropertyInfo p in GetType().GetProperties())
            {
                p.SetValue(cell, p.GetValue(this));
            }
            return cell;
        }

        public virtual void FindAllProperty(out List<string> propertienames, out List<object> values)
        {
            Type type = GetType();
            propertienames = new List<string>();
            values = new List<object>();
            foreach (PropertyInfo p in type.GetProperties())
            {
                object v = p.GetValue(this);
                propertienames.Add(p.Name);
                values.Add(v);
            }
        }
        public virtual void FindAllPropertyChanged(out List<string> propertienames, out List<object> values)
        {
            Type type = GetType();
            propertienames = new List<string>();
            values = new List<object>();
            if (beforesetsqlinformation != null)//zys 20230306
            {
                foreach (PropertyInfo p in type.GetProperties())
                {
                    object vorigin = p.GetValue(beforesetsqlinformation);
                    object v = p.GetValue(this);
                    if (vorigin == null)
                    {
                        if (v == null)
                        {

                        }
                        else
                        {
                            propertienames.Add(p.Name);
                            values.Add(v);
                        }
                    }
                    else if (!vorigin.Equals(v))
                    {
                        propertienames.Add(p.Name);
                        values.Add(v);
                    }
                }
            }
        }

        public virtual void SetSqlInformation()
        {
            List<string> listnames;
            List<object> values;
            this.FindAllPropertyChanged(out listnames, out values);
            Window window = ((ObserveCollectionManage)(ParentSqlInformationCollection.GetType().GetProperty("ObserveCollectionManage").GetValue(ParentSqlInformationCollection))).Window;
            if (window != null)
            {
                if (window.Dispatcher.CheckAccess())
                {
                    for (int i = 0; i < listnames.Count; i++)
                    {
                        OnPropertyChanged(this, new PropertyChangedEventArgs(listnames[i]));
                    }
                }
                else
                {
                    window.Dispatcher.BeginInvoke(new Action<SqlInformationBase, List<string>>((sqlInformationBase, strings) =>
                    {
                        for (int i = 0; i < strings.Count; i++)
                        {
                            OnPropertyChanged(sqlInformationBase, new PropertyChangedEventArgs(strings[i]));
                        }
                    }), this, listnames);
                }
            }

            if (listnames.Count == 0 || values.Count == 0)
            {
                return;
            }
            if (PrimaryKey != null)
            {
                if (ParentSqlInformationCollection.SqlClient.Update(ParentSqlInformationCollection.TableName, [PrimaryKey], [PrimaryKeyValue], listnames.ToArray(), values.ToArray()))
                {
                }
                else
                {
                    throw new Exception($"数据库更新信息异常PrimaryKey:{PrimaryKey},PrimaryKeyValue{PrimaryKeyValue}\r\n详细信息：\r\n变量名：{listnames.ToArray().ToString(",")}\r\n值：{values.ToArray().ToString(",")}");
                }
            }
            else
            {
                throw new Exception("不存在关键字或者元素字");
            }
        }

        public virtual void RemoveSqlInformation()
        {
            ISqlCollectionBase sqlInformationCollection = ParentSqlInformationCollection;
            if (!string.IsNullOrEmpty(PrimaryKey))
            {
                sqlInformationCollection.SqlClient.DeleteData(sqlInformationCollection.TableName, [PrimaryKey], [PrimaryKeyValue]);
            }
            else if (Key != null)
            {
                sqlInformationCollection.RemoveKeyData(KeyValue);
            }
            else if (Element != null)
            {
                sqlInformationCollection.RemoveElementData(ElementValue);
            }
            else
            {
                throw new Exception("不存在关键字或者元素字");
            }
        }
    }

    public class SqlInformationCollection<T>: ISqlInformationCollection where T : SqlInformationBase ,new()
    {
        public ObserveCollectionManage ObserveCollectionManage 
        { 
            get; 
            set; 
        } = new ObserveCollectionManage();

        public event Action<T> OnCreateNewSqlInformation;
        private ISqlClient sqlClient;
        public string table;
        private string[] key;
        public string[] Element;
        private Type resgistType;
        public Type ResgistType => resgistType;
        public string[] Key
        {
            get { return key; }
            set
            {
                key = value;
            }
        }

        public string PrimaryKey { get;set; }

        public SqlInformationCollection() : this(null, null, typeof(T), null)
        {

        }


        public SqlInformationCollection(ISqlClient _sqlClient, string _tablename, params string[] _Key) : this(_sqlClient, _tablename, typeof(T), _Key)
        {

        }


        private SqlInformationCollection(ISqlClient _sqlClient, string _tablename, Type resgistType, params string[] _Key)
        {
            sqlClient = _sqlClient;
            table = _tablename;
            key = _Key;
            this.resgistType = resgistType;
        }

        public T CreateOne( params object[] vals)
        {
            return (T)((ISqlInformationCollection)this).CreateNewSqlInformation(vals);
        }

        public bool GetOne(out T data, params object[] vals)
        {
            data = null;
            try
            {
                data = (T)((ISqlInformationCollection)this).GetElementOneSqlInformation(FirstOrLast.Last, Key, vals);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public T GetOrCreateOne(params object[] vals)
        {
            if (GetOne(out var data, vals))
            {
                return data;
            }
            return CreateOne(vals);
        }



        public ISqlClient SqlClient
        {
            get { return sqlClient; }
            set
            {
                sqlClient = value;
            }
        }

        public string TableName
        {
            get { return table; }
            set
            {
                table = value;
            }
        }



        public T this[params string[] _KeyValue]
        {
            get
            {

                return GetKeySqlInformation(_KeyValue);

            }
        }

        public SqlInformationCollection<T> ToSqlInformationCollectionBase()
        {
            SqlInformationCollection<T> sqlInformationCollection = new SqlInformationCollection<T>(sqlClient, table, key);
            return sqlInformationCollection;
        }



        public virtual T CreateNewSqlInformation(params object[] _KeyValue)
        {
            SqlInformationBase cell = Activator.CreateInstance(resgistType) as SqlInformationBase;
            cell.PrimaryKey = this.PrimaryKey;
            cell.ParentSqlInformationCollection = this;
            cell.Key = key;
            cell.KeyValue = _KeyValue;
            if (key.Length != _KeyValue.Length)
            {
                throw new Exception("关键字和关键值数量不一致，无法匹配");
            }
            for (int i = 0; i < key.Length; i++)
            {
                cell.GetType().GetProperty(key[i]).SetValue(cell, _KeyValue[i]);
            }
            List<string> listnames;
            List<object> values;
            cell.FindAllProperty(out listnames, out values);
            long id = 0;
            if (sqlClient.Insert(table, listnames.ToArray(), values.ToArray(), ref id))
            {
                //DataSet ds = newSQL.SqlClient.GetData(table, cell.PrimaryKey, id.ToString());
                cell.PrimaryKeyValue = id;
                cell = GetElementSqlInformation(new string[] { cell.PrimaryKey }, new object[] { id })[0];
                cell.SetBeforeSqlInformation(cell.Copy());
                if (ObserveCollectionManage.Window != null)
                {
                    if (ObserveCollectionManage.Window.Dispatcher.CheckAccess())
                    {
                        ObserveCollectionManage.Add(cell);
                    }
                    else
                    {
                        ObserveCollectionManage.Window.Dispatcher.Invoke(new Action<T>(t =>
                        {
                            ObserveCollectionManage.Add(t);
                        }), cell);
                    }
                }
                OnCreateNewSqlInformation?.Invoke((T)cell);
            }
            else
            {
                throw new Exception($"数据库插入信息异常\r\n详细信息：\r\n变量名：{listnames.ToArray().ToString(",")}\r\n值：{values.ToArray().ToString(",")}");
            }
            return (T)cell;
        }

        public T GetKeySqlInformation(params object[] _KeyValue)
        {
            SqlInformationBase cell = Activator.CreateInstance(resgistType) as SqlInformationBase;
            cell.PrimaryKey = this.PrimaryKey;
            cell.ParentSqlInformationCollection = this;
            cell.Key = key;
            cell.KeyValue = _KeyValue;
            DataSet dataSet = sqlClient.GetData(table, key, _KeyValue);
            if (key.Length != _KeyValue.Length)
            {
                throw new Exception("关键字和关键值数量不一致，无法匹配");
            }
            if (dataSet.Tables[0].Rows.Count == 1)
            {
                cell.PrimaryKeyValue = dataSet.Tables[0].Rows[0].Field<object>((string)cell.PrimaryKey);
                foreach (PropertyInfo p in typeof(T).GetProperties())
                {
                    object v = dataSet.Tables[0].Rows[0].Field<object>(p.Name);
                    p.SetValue(cell, v);
                }
                cell.SetBeforeSqlInformation(cell.Copy());
                return (T)cell;
            }
            else if (dataSet.Tables[0].Rows.Count > 1)
            {
                throw new Exception($"获取到关键字{_KeyValue.ToString(",")}的行数大于1");
            }
            else
            {
                throw new Exception($"查询到的数据库信息为空\r\n关键字：{key.ToString(",")}，值{_KeyValue.ToString(",")}");
            }

        }

        public void SetElement(params string[] _Element)
        {
            Element = _Element;
        }

        public T[] GetElementSqlInformation(string[] _Element, params object[] _ElementValue)
        {

            string[] Element = _Element;
            List<T> cells = new List<T>();
            DataSet dataSet = sqlClient.GetData(table, Element, _ElementValue);
            if (dataSet.Tables[0].Rows.Count > 0)
            {
                for (int k = 0; k < dataSet.Tables[0].Rows.Count; k++)
                {
                    SqlInformationBase cell = Activator.CreateInstance(resgistType) as SqlInformationBase;
                    cell.PrimaryKey = this.PrimaryKey;
                    cell.ParentSqlInformationCollection = this;
                    cell.Element = Element;
                    cell.ElementValue = _ElementValue;
                    if (cell.Element.Length != cell.ElementValue.Length)
                    {
                        throw new Exception("查询字和查询值数量不一致，无法匹配");
                    }
                    cell.PrimaryKeyValue = dataSet.Tables[0].Rows[k].Field<object>((string)cell.PrimaryKey);
                    foreach (PropertyInfo p in resgistType.GetProperties())
                    {
                        object v = dataSet.Tables[0].Rows[k].Field<object>(p.Name);
                        p.SetValue(cell, v);
                    }
                    cell.SetBeforeSqlInformation(cell.Copy());
                    cells.Add((T)cell);
                }
                return cells.ToArray();
            }
            else
            {
                throw new Exception($"查询到的数据库元素数量为空\r\n查询元素：{Element.ToString(",")}值：{_ElementValue.ToString(",")}");
            }
        }


        public virtual T GetElementOneSqlInformation(FirstOrLast firstOrLast, string[] _Element, params object[] _ElementValue)
        {
            string[] Element = _Element;
            List<T> cells = new List<T>();
            DataSet dataSet;
            if (firstOrLast == FirstOrLast.Last)
            {
                dataSet = sqlClient.GetNewData(table, Element, _ElementValue);
            }
            else
            {
                dataSet = sqlClient.GetFirstData(table, Element, _ElementValue);
            }
            if (dataSet.Tables[0].Rows.Count > 0)
            {
                SqlInformationBase cell = Activator.CreateInstance(resgistType) as SqlInformationBase;
                cell.PrimaryKey = this.PrimaryKey;
                cell.ParentSqlInformationCollection = this;
                cell.Element = Element;
                cell.ElementValue = _ElementValue;
                if (cell.Element.Length != cell.ElementValue.Length)
                {
                    throw new Exception("查询字和查询值数量不一致，无法匹配");
                }
                cell.PrimaryKeyValue = dataSet.Tables[0].Rows[0].Field<object>((string)cell.PrimaryKey);

                if (ObserveCollectionManage.CellDic.ContainsKey(cell.PrimaryKeyValue))
                {
                    T ff = (T)ObserveCollectionManage.CellDic[cell.PrimaryKeyValue];
                    ff.SetBeforeSqlInformation(ff.Copy());
                    return ff;
                }
                else
                {
                    foreach (PropertyInfo p in resgistType.GetProperties())
                    {
                        object v = dataSet.Tables[0].Rows[0].Field<object>(p.Name);
                        p.SetValue(cell, v);
                    }
                    cell.SetBeforeSqlInformation(cell.Copy());
                    return (T)cell;
                }

            }
            else
            {
                throw new Exception($"查询到的数据库元素数量为空\r\n查询元素：{Element.ToString(",")}值：{_ElementValue.ToString(",")}");
            }
        }

        public T GetElementOneSqlInformation(string _Element, object _ElementValue)
        {
            return GetElementOneSqlInformation(FirstOrLast.Last, new string[] { _Element }, _ElementValue);
        }

        public T GetNextSqlInformation(SqlInformationBase sqlInformationBase, long MaxNextNum)
        {
            // Element = sqlInformationBase.Element;
            //List<T> cells = new List<T>();
            DataSet dataSet;
            long id = (long)sqlInformationBase.PrimaryKeyValue;

            while (true)
            {
                id++;
                dataSet = sqlClient.GetData(table, sqlInformationBase.PrimaryKey, id.ToString());
                if (dataSet.Tables[0].Rows.Count > 0)
                {
                    SqlInformationBase cell = Activator.CreateInstance(resgistType) as SqlInformationBase;
                    cell.PrimaryKey = this.PrimaryKey;
                    cell.ParentSqlInformationCollection = this;
                    cell.PrimaryKeyValue = dataSet.Tables[0].Rows[0].Field<object>((string)cell.PrimaryKey);
                    foreach (PropertyInfo p in typeof(T).GetProperties())
                    {
                        object v = dataSet.Tables[0].Rows[0].Field<object>(p.Name);
                        p.SetValue(cell, v);
                    }
                    cell.SetBeforeSqlInformation(cell.Copy());
                    return (T)cell;
                }
                else
                {
                    if (id - (long)sqlInformationBase.PrimaryKeyValue > MaxNextNum)
                    {
                        T cell = default(T);
                        cell.SetBeforeSqlInformation(cell.Copy());
                        return default(T);
                        //throw new Exception($"查询到的数据库元素数量为空\r\n查询上层信息为：{sqlInformationBase.PrimaryKey},值：{sqlInformationBase.PrimaryKeyValue },下层id间距{MaxNextNum}");

                    }
                }
            }
        }




        public T GetLastSqlInformation()
        {
            SqlInformationBase cell = Activator.CreateInstance(resgistType) as SqlInformationBase;
            cell.PrimaryKey = this.PrimaryKey;
            cell.ParentSqlInformationCollection = this;
            cell.Key = key;
            Stopwatch sw = new Stopwatch();
            DataSet dataSet = sqlClient.FindLastData(table );
            if (dataSet.Tables[0].Rows.Count == 1)
            {
                cell.PrimaryKeyValue = dataSet.Tables[0].Rows[0].Field<object>((string)cell.PrimaryKey);
                foreach (PropertyInfo p in typeof(T).GetProperties())
                {
                    object v = dataSet.Tables[0].Rows[0].Field<object>(p.Name);
                    p.SetValue(cell, v);
                }
                cell.SetBeforeSqlInformation(cell.Copy());
                return (T)cell;
            }
            else if (dataSet.Tables[0].Rows.Count > 1)
            {
                throw new Exception($"获取到的行数大于1");
            }
            else
            {
                throw new Exception($"查询到的数据库最后一行信息为空\r\n关键字：{key.ToString(",")}");
            }
        }

        public T GetFirstSqlInformation()
        {

            SqlInformationBase cell = Activator.CreateInstance(resgistType) as SqlInformationBase;
            cell.PrimaryKey = this.PrimaryKey;
            cell.ParentSqlInformationCollection = this;
            cell.Key = key;
            DataSet dataSet = sqlClient.FindFirstData(table);
            if (dataSet.Tables[0].Rows.Count == 1)
            {
                cell.PrimaryKeyValue = dataSet.Tables[0].Rows[0].Field<object>((string)cell.PrimaryKey);
                foreach (PropertyInfo p in typeof(T).GetProperties())
                {
                    object v = dataSet.Tables[0].Rows[0].Field<object>(p.Name);
                    p.SetValue(cell, v);
                }
                cell.SetBeforeSqlInformation(cell.Copy());
                return (T)cell;
            }
            else if (dataSet.Tables[0].Rows.Count > 1)
            {
                throw new Exception($"获取到的行数大于1");
            }
            else
            {
                throw new Exception($"查询到的数据库第一行信息为空\r\n关键字：{key.ToString(",")}");
            }

        }

        public T[] GetLastCountSqlInformation(int lastcount)
        {

            List<T> cells = new List<T>();

            DataSet dataSet = sqlClient.FindLastLines(table, lastcount);
            if (dataSet.Tables[0].Rows.Count > 0)
            {
                for (int k = 0; k < dataSet.Tables[0].Rows.Count; k++)
                {
                    SqlInformationBase cell = Activator.CreateInstance(resgistType) as SqlInformationBase;
                    cell.PrimaryKey = this.PrimaryKey;
                    cell.ParentSqlInformationCollection = this;
                    cell.PrimaryKeyValue = dataSet.Tables[0].Rows[k].Field<object>((string)cell.PrimaryKey);
                    foreach (PropertyInfo p in typeof(T).GetProperties())
                    {
                        object v = dataSet.Tables[0].Rows[k].Field<object>(p.Name);
                        p.SetValue(cell, v);
                    }
                    cell.SetBeforeSqlInformation(cell.Copy());
                    cells.Add((T)cell);
                }
                return cells.ToArray();
            }
            else
            {
                throw new Exception($"查询到的数据库数量为空\r\n查询表：{table} 最后几个数量：{lastcount}");
            }

        }


        public void RemoveKeyData(params object[] values)
        {


            int ret = sqlClient.DeleteData(table, key, values);
            if (ret == 0)
            {
                throw new Exception($"需要删除的关键字{key.ToString(",")}={values.ToString(",")}行未找到");
            }


        }
        public void RemoveElementData(params object[] values)
        {
            int ret = sqlClient.DeleteData(table, Element, values);
            if (ret == 0)
            {
                throw new Exception($"需要删除的关键字{Element.ToString(",")}={values.ToString(",")}行未找到");
            }
        }

        SqlInformationBase ISqlInformationCollection.CreateNewSqlInformation(params object[] _KeyValue)
        {
            return this.CreateNewSqlInformation(_KeyValue);
        }

        SqlInformationBase ISqlInformationCollection.GetElementOneSqlInformation(FirstOrLast firstOrLast, string[] _Element, params object[] _ElementValue)
        {
            return this.GetElementOneSqlInformation(firstOrLast, _Element, _ElementValue);
        }

        SqlInformationBase ISqlInformationCollection.GetElementOneSqlInformation(string _Element, object _ElementValue)
        {
            return GetElementOneSqlInformation(_Element, _ElementValue);
        }

        SqlInformationBase[] ISqlInformationCollection.GetElementSqlInformation(string[] _Element, params object[] _ElementValue)
        {
            return GetElementSqlInformation(_Element, _ElementValue).Cast<SqlInformationBase>().ToArray();
        }

        SqlInformationBase ISqlInformationCollection.GetFirstSqlInformation()
        {
            return GetFirstSqlInformation();
        }

        SqlInformationBase ISqlInformationCollection.GetKeySqlInformation(params object[] _KeyValue)
        {
            return GetKeySqlInformation();
        }

        SqlInformationBase[] ISqlInformationCollection.GetLastCountSqlInformation(int lastcount)
        {
            return GetLastCountSqlInformation(lastcount).Cast<SqlInformationBase>().ToArray();
        }

        SqlInformationBase ISqlInformationCollection.GetLastSqlInformation()
        {
            return GetLastSqlInformation();
        }

        SqlInformationBase ISqlInformationCollection.GetNextSqlInformation(SqlInformationBase sqlInformationBase, long MaxNextNum)
        {
            return GetNextSqlInformation(sqlInformationBase, MaxNextNum);
        }
    }

    public class ObserveCollectionManage
    {
        private int maxCount = 10;
        public int MaxCount
        {
            get { return maxCount; }
            set { maxCount = value; }
        }

        public Window Window { get; set; }

        public ObservableCollection<SqlInformationBase> ObservableCollection { get; set; } = new ObservableCollection<SqlInformationBase>();
        internal Dictionary<object, SqlInformationBase> CellDic { get; set; } = new Dictionary<object, SqlInformationBase>();
        public void Add(SqlInformationBase obj)
        {
            lock (this)
            {
                ObservableCollection.Add(obj);
                CellDic.Add(obj.PrimaryKeyValue.ToInt64(), obj);
                if (ObservableCollection.Count > maxCount)
                {
                    CellDic.Remove(ObservableCollection[0].PrimaryKeyValue.ToInt64());
                    ObservableCollection.RemoveAt(0);

                }
            }
        }

        public SqlInformationBase GetByIndex(long index)
        {
            return CellDic[index];
        }
    }
}
